import {Component, OnInit} from "@angular/core";
import {PermissionType, AppConstants} from "../../../constants/constants";
import {PortalUtilService} from "../../portal-util.service";
import {PortalsService} from "../../portals.service";
import {MsgResult} from "../../../models/msg-result";
import {Menu} from "../../../models/menu";
import {ResponseUtil} from "../../../util/response-util";
import {TreeUtil} from "../../../util/tree-util";
import {Observable} from "rxjs/Observable";

declare var $;

@Component({
  selector: 'app-admin-sidebar',
  templateUrl: './admin-sidebar.component.html'
})
export class AdminSidebarComponent implements OnInit{

  menus : Menu[];

  constructor(
    private portalsService : PortalsService,
    private portalUtilService: PortalUtilService,
    private responseUtil : ResponseUtil,
    private treeUtil : TreeUtil
  ) { }

  ngOnInit() {
    this.initAdminLte();
    this.getMenus();
  }
  initAdminLte() {
    if (!$.AdminLTE) {
      this.portalUtilService.initAdminLte();
    }
  }
  private getMenus(){
    this.getMenusByConfig().subscribe(
        result => this.responseUtil.success(result,this.process),
        error => this.responseUtil.error(error)
      );
  }

  private getMenusByConfig():Observable<any>{
    if(AppConstants.sysId){
      return this.portalsService.getChildMenus(AppConstants.sysId);
    }else{
      return this.portalsService.getPermissions(PermissionType.menus);
    }
  }

  private process = (result : MsgResult) => {
    let rootId = AppConstants.sysId ? AppConstants.sysId : null;
    let rootNode = {id:rootId};
    let ownedMneus:any= this.treeUtil.filterNodes(rootNode,result.data);
    if(ownedMneus.length == 0){
      this.menus = [];
    }else{
      this.menus = ownedMneus[0].children;
    }
  }
}
